<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>1.灰度化图片</title>
    <style>
        canvas{
            border:1px solid #aaa;
            margin: 0 auto;
            display: block;
        }
    </style>
</head>
<body>
    <canvas width="0" height="0"></canvas>

    <script type="module">

        import { loadImage, getImageData, traverse } from "/common/lib/utils.js"
        const canvas = document.querySelector('canvas'); 
        const context = canvas.getContext('2d');
        (async function(){
            // 异步加载图片
            let img = await loadImage('https://p2.ssl.qhimg.com/d/inn/4b7e384c55dc/girl1.jpg');
            
            // 获取图片剪裁区的数据 imgData（包含了图片的所有像素数据）
            const imageData = getImageData(img)
            
            // 循环遍历 imageData 数据，并处理
            traverse(imageData,({r, g, b, a}) => { 
                // 对每个像素进行灰度化处理
                const v = 0.2126 * r + 0.7152 * g + 0.0722 * b;
                return [v, v, v, a];
            });
            canvas.width = img.width
            canvas.height = img.height
            context.putImageData(imageData,0,0)
        })()


    </script>
</body>
</html>